package com.vecharm.app.manager

import android.util.Log
import com.google.gson.Gson
import com.ling.sdk.utils.Toasty
import com.tencent.bugly.beta.Beta
import com.vecharm.app.api.API
import com.vecharm.app.bean.GoodsBean
import com.vecharm.app.bean.SessionBean
import com.vecharm.app.utils.getService
import com.vecharm.app.utils.request
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.concurrent.TimeUnit

object GoodsManager {

    var callBack: (() -> Unit)? = null

    private var isStarted = false


    fun start() {

        if (isStarted) return

        request()

        Observable.interval(SessionBean.getSession().interval, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe { request() }
    }


    private fun request() {

        isStarted = true

        currentGoodsVersion = getVersion()

        Log.e("GoodsLog", "version:$currentGoodsVersion")


        Toasty.showInfo("刷新")

        getService<API>().getGoods(currentGoodsVersion).request {
            onSuccess = {
                Log.e("GoodsLog", Gson().toJson(it))
                if (it.checkUpdate) { //检查更新
                    Beta.checkUpgrade(true, true)
                }
                if (currentGoodsVersion < it.goodsVersion) {
                    it.save()
                    // 如果当前的版本号小于最新的版本号 ，那么就进行更新
                    currentGoodsVersion = it.goodsVersion
                    callBack?.invoke()
                }
            }

            onErrorMessage = { code, error ->
                Log.e("GoodsLog", "$error[$code]")
                Toasty.showInfo("$error[$code]")
            }
        }

    }

    private var currentGoodsVersion = 0

    private fun getVersion(): Int {
        val goods = GoodsBean.getGoods() ?: return 0
        if (goods.goods?.isEmpty() != false) return 0
        return goods.goodsVersion
    }

}